#include "savedata.h"
#include <QDebug>

SaveData * SaveData::datafile = nullptr;

SaveData::SaveData()
{
    dir = new QDir("./history_data/");
    //如果存储历史数据的文件夹不存在，则创建
    if(!dir->exists()){
        dir->mkdir(dir->absolutePath());
        //qDebug() << "创建文件夹路径:" << dir->absolutePath();
    }else {
        //qDebug() << "路径存在:" << dir->absolutePath();
    }

    file = new QFile(dir->absolutePath() + "/" + QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss") + ".csv");

    if(file->open(QIODevice::WriteOnly | QIODevice::Text)){
        QString str = "传感器重量，五路热电偶温度，加热炉开断情况，五路阀门开端状态，推杆高度，电机转速，加热炉功率，时间日期\n";
        QTextStream in(file);
        in.setCodec("UTF-8");
        in << str;
        file->close();
    }else{
        emit saveDataOpenFileDefeat(file->error());
    }
}

SaveData *SaveData::getInstance()
{
    if(datafile == nullptr){
        datafile = new SaveData;
    }

    return datafile;
}

SaveData::~SaveData()
{
    if(dir != nullptr)
        delete dir;

    if(file != nullptr)
        delete file;
}

void SaveData::saveData(QString info)
{
    if(file->open(QIODevice::Append | QIODevice::Text))
    {
        QTextStream out(file);
        out.setCodec("UTF-8");
        out << info << "\n";
        file->close();
    }else{
        //qDebug() << "SAVE_ERROR:file open error";
        emit saveDataOpenFileDefeat(file->error());
    }
}
